#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv[]){
    printf("system_bootstrap pid:%d\n", getpid());
    char *program = "#include <stdio.h>\n"
            "#include <stdlib.h>\n"
            "#include <unistd.h>\n"
            "int result;\n"
            "int main(int argc, char *argv[]){\n"
            "printf(\"main_add pid: %d\\n\", getpid());\n"
            "int a = 0;\n"
            "int b = 0;\n"
            "a = atoi(argv[2]);\n"
            "b = atoi(argv[3]);\n"
            "char op = *argv[1];\n"
            "switch (op){\n"
            "case '+':\n"
            "result = a + b;\n"
            "break;\n"
            "case '-':\n"
            "result = a - b;\n"
            "break;\n"
            "case '*':\n"
            "result = a * b;\n"
            "break;\n"
            "case '/':\n"
            "result = a / b;\n"
            "break;\n"
            "default:\n"
            "printf(\"input error!\\n\");\n"
            "//exit(-1);\n"
            "}\n"
            "printf(\"%d %c %d = %d\\n\", a, op, b, result);\n"
            "return 0;\n"
            "}\n";
    // printf("%s\n", program);
    int fd_math_c = creat("./math.c", S_IRUSR | S_IWUSR);
    printf("fd for math.c file: %d\n", fd_math_c);
    write(fd_math_c, program, strlen(program));

    int fd_cc = open("/etc/alternatives/cc", O_RDONLY);
    // int fd_cc = open("/usr/bin/gcc", O_RDONLY);
    printf("fd of cc: %d\n", fd_cc);
    char *ccargv[] = {"cc", "./math.c", "-o", "math", NULL};
    char *newenviron[] = {NULL};
    int res = fexecve(fd_cc, ccargv, newenviron);
	// printf("%d\n", res);

    // system("cc ./math.c -o math");
    system("./math + 10 40");
}
